package com.dony.shop.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dony.common.utils.StringUtils;
import com.dony.shop.service.ShopeeAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Map;

/**
 * @author sundw
 * @version 1.0.0
 * @description ShopeeUitl
 * @since 2022/8/26 15:38
 */
@Slf4j
@Component
public class ShopeeUtil {

    @Value("${shopee.parent_id}")
    private Integer parentId;

    @Value("${shopee.key}")
    private String key;

    @Value("${shopee.api_host}")
    private String host;

    @Resource
    ShopeeAuthService shopeeAuthService;


    /**
     * 发送get请求
     *
     * @param merchantId
     * @param paramMap
     * @return
     */
    public JSONObject merchantGetHandler(String path, Long merchantId, Map<String, Object> paramMap) {
        long timestamp = System.currentTimeMillis() / 1000L;
        String accessToken = shopeeAuthService.getMerchantAccessToken(merchantId);
        String baseString = parentId + path + timestamp + accessToken + merchantId;
        String sign = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, key).digestHex(baseString);
        String url = host + path + "?partner_id=" + parentId + "&timestamp=" + timestamp + "&access_token=" + accessToken + "&merchant_id=" + merchantId + "&sign=" + sign;
        String postResult = HttpUtil.get(url, paramMap);
        JSONObject reslut = JSONObject.parseObject(postResult);
        //如果有数据
        if (StringUtils.isEmpty(reslut.getString("error"))) {
            JSONObject response = reslut.getJSONObject("response");
            //log.info("商家get请求成功，merchantId:{} , request:{}, response{}", merchantId, JSON.toJSONString(paramMap), response.toString());
            return response;
        }
        log.error("商户GET请求失败! 错误信息：{} /n 请求地址地址:{} /n 商户Id:{} /n 请求信息:{} /n 返回值:{}", reslut.getString("error"), url, merchantId, JSON.toJSONString(paramMap), postResult);
        return null;
    }

    /**
     * 发送post请求
     *
     * @param merchantId
     * @param paramMap
     * @return
     */
    public JSONObject merchantPostHandler(String path, Long merchantId, Map<String, Object> paramMap) {
        long timestamp = System.currentTimeMillis() / 1000L;
        String accessToken = shopeeAuthService.getMerchantAccessToken(merchantId);
        String baseString = parentId + path + timestamp + accessToken + merchantId;
        String sign = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, key).digestHex(baseString);
        String url = host + path + "?partner_id=" + parentId + "&timestamp=" + timestamp + "&access_token=" + accessToken + "&merchant_id=" + merchantId + "&sign=" + sign;
        String postResult = HttpUtil.post(url, JSON.toJSONString(paramMap));
        JSONObject reslut = JSONObject.parseObject(postResult);
        //如果有数据
        if (StringUtils.isEmpty(reslut.getString("error"))) {
            JSONObject response = reslut.getJSONObject("response");
            //log.info("商家post请求成功，merchantId:{} , request:{}, response{}", merchantId, JSON.toJSONString(paramMap), response.toString());
            return response;
        }
        log.error("商户POST请求失败! 错误信息：{} /n 请求地址地址:{} /n 商户Id:{} /n 请求信息:{} /n 返回值:{}", reslut.getString("error"), url, merchantId, JSON.toJSONString(paramMap), postResult);
        return null;
    }

    /**
     * 发送post请求
     *
     * @param shopId
     * @param paramMap
     * @return
     */
    public JSONObject shopPostHandler(String path, Long shopId, Map<String, Object> paramMap) {
        long timestamp = System.currentTimeMillis() / 1000L;
        String accessToken = shopeeAuthService.getShopAccessToken(shopId);
        String baseString = parentId + path + timestamp + accessToken + shopId;
        String sign = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, key).digestHex(baseString);
        String url = host + path + "?partner_id=" + parentId + "&timestamp=" + timestamp + "&access_token=" + accessToken + "&shop_id=" + shopId + "&sign=" + sign;
        String postResult = HttpUtil.post(url, JSON.toJSONString(paramMap));
        JSONObject reslut = JSONObject.parseObject(postResult);
        //如果有数据
        if (StringUtils.isEmpty(reslut.getString("error"))) {
            JSONObject response = reslut.getJSONObject("response");
            //log.info("店铺post请求成功，shopId:{} , request:{}, response{}", shopId, JSON.toJSONString(paramMap), response.toString());
            return response;
        }
        log.error("店铺POST请求失败! 错误信息：{} /n 请求地址地址:{} /n 店铺Id:{} /n 请求信息:{} /n 返回值:{}", reslut.getString("error"), url, shopId, JSON.toJSONString(paramMap), postResult);
        return null;
    }

    /**
     * 发送get请求
     *
     * @param shopId
     * @param paramMap
     * @return
     */
    public JSONObject shopGetHandler(String path, Long shopId, Map<String, Object> paramMap, String extraPath) {
        long timestamp = System.currentTimeMillis() / 1000L;
        String accessToken = shopeeAuthService.getShopAccessToken(shopId);
        String baseString = parentId + path + timestamp + accessToken + shopId;
        String sign = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, key).digestHex(baseString);
        String url = host + path + "?partner_id=" + parentId + "&timestamp=" + timestamp + "&access_token=" + accessToken + "&shop_id=" + shopId + "&sign=" + sign;
        if (StringUtils.isNotEmpty(extraPath)) {
            url += extraPath;
        }
        String postResult = HttpUtil.get(url, paramMap);
        JSONObject reslut = JSONObject.parseObject(postResult);
        //如果有数据
        if (StringUtils.isEmpty(reslut.getString("error"))) {
            JSONObject response = reslut.getJSONObject("response");
            //log.info("店铺get请求成功，shopId:{} , request:{}, response{}", shopId, JSON.toJSONString(paramMap), response.toString());
            return response;
        }
        log.error("店铺GET请求失败! 错误信息：{} /n 请求地址地址:{} /n 店铺Id:{} /n 请求信息:{} /n 返回值:{}", reslut.getString("error"), url, shopId, JSON.toJSONString(paramMap), postResult);
        return null;
    }


    /**
     * 发送get请求
     *
     * @param shopId
     * @param paramMap
     * @return
     */
    public JSONObject shopGetHandler(String path, Long shopId, Map<String, Object> paramMap) {
        return shopGetHandler(path, shopId, paramMap, null);
    }

    /**
     * 下载文件保存操作
     *
     * @param url
     * @param paramMap
     * @param filePath
     * @return
     */
    public byte[] downloadFile(String path, Long shopId, Map<String, Object> paramMap) {
        long timestamp = System.currentTimeMillis() / 1000L;
        String accessToken = shopeeAuthService.getShopAccessToken(shopId);
        String baseString = parentId + path + timestamp + accessToken + shopId;
        String sign = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, key).digestHex(baseString);
        String url = host + path + "?partner_id=" + parentId + "&timestamp=" + timestamp + "&access_token=" + accessToken + "&shop_id=" + shopId + "&sign=" + sign;
        HttpResponse response = HttpRequest.post(url).timeout(-1).body(JSON.toJSONString(paramMap)).executeAsync();
        if (!response.isOk()) {
            log.error("下载文件失败！服务器返回的错误码: [{}]", response.getStatus());
            return null;
        }
        return response.bodyBytes();
    }


    /**
     * 上传图片文件到shopee
     */
    public String uploadFile(File file) {
        long timestamp = System.currentTimeMillis() / 1000L;
        String uri = "/api/v2/media_space/upload_image";
        String baseString = parentId + uri + timestamp;
        String sign = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, key).digestHex(baseString);
        String url = host + uri + "?partner_id=" + parentId + "&timestamp=" + timestamp + "&sign=" + sign;
        String postResult = HttpRequest.post(url).timeout(-1).form("image", file).executeAsync().body();
        JSONObject reslut = JSONObject.parseObject(postResult);
        //如果有数据
        if (StringUtils.isEmpty(reslut.getString("error"))) {
            JSONObject response = reslut.getJSONObject("response");
            //image_info
            //image_id
            //image_url_list   image_url_region   image_url
            JSONObject imageInfo = response.getJSONObject("image_info");
            return imageInfo.getString("image_id");
            /*List<JSONObject> imageUrlList = imageInfo.getList("image_url_list", JSONObject.class);
            //JSONArray imageUrlList = imageInfo.getJSONArray("image_url_list");
            for (JSONObject image : imageUrlList) {
                if (StringUtils.equals(image.getString("image_url_region").toLowerCase(), "ph")) {
                    return image.getString("image_url");
                }
            }*/
        }
        log.error("上传图片文件到shopee失败！错误信息:{} /n 请求地址:{} /n 返回结果:{}", reslut.getString("error"), url, postResult);
        return null;

    }


}
